package gold.digger;

import gold.utils.InputUtil;

import java.util.*;
import java.util.List;

/**
 * Created by fanzhenyu02 on 2020/6/27.
 * common problem solver template.
 */
public class LC915 {
    public long startExecuteTime = System.currentTimeMillis();


    class Solution {
        public int partitionDisjoint(int[] nums) {
            int[] pre = new int[nums.length], after = new int[nums.length];
            int curPreMax = 0, curAfterMin = Integer.MAX_VALUE;
            for (int i = 0; i < nums.length; i++) {
                curPreMax = Math.max(curPreMax, nums[i]);
                pre[i] = curPreMax;
            }

            for (int i = nums.length - 1; i >= 0; i--) {
                curAfterMin = Math.min(curAfterMin, nums[i]);
                after[i] = curAfterMin;
            }

            for (int i = 0; i < nums.length - 1; i++) {
                if (pre[i] <= after[i + 1]) return i + 1;
            }

            return nums.length - 1;
        }
    }


    class Solution_Time_Exceed {
        public int partitionDisjoint(int[] nums) {
            PriorityQueue<Integer> pre = new PriorityQueue<>(Comparator.reverseOrder()), after = new PriorityQueue<>();
            pre.add(nums[0]);
            for (int i = 1; i < nums.length; i++) {
                after.add(nums[i]);
            }

            for (int i = 1; i < nums.length; i++) {
                if (pre.peek() <= after.peek()) return i;
                pre.add(nums[i]);
                after.remove(nums[i]);
            }

            return nums.length - 1;
        }
    }

    public void run() {
        Solution solution = new Solution();
        int[] arr = InputUtil.toIntegerArray("[5,0,3,8,6]");
        System.out.println(solution.partitionDisjoint(arr));

        int[] arr2 = InputUtil.toIntegerArray("[1,1,1,0,6,12]");
        System.out.println(solution.partitionDisjoint(arr2));

        int[] arr3 = InputUtil.toIntegerArray("[26,51,40,58,42,76,30,48,79,91]");
        System.out.println(solution.partitionDisjoint(arr3));


    }

    public static void main(String[] args) throws Exception {
        LC915 an = new LC915();
        an.run();

        System.out.println("\ncurrent solution total execute time: " + (System.currentTimeMillis() - an.startExecuteTime) + " ms.");
    }
}
